package test.threads.sync;

import java.util.ArrayList;
import java.util.List;

public class WorkerPool {

	private static List<Worker> workers = createWorkersList();

	private static List<Worker> createWorkersList() {

		List<Worker> workers = new ArrayList<Worker>();

		for (int i = 0; i < 5; i++) {
			workers.add(new Worker("" + i));
		}

		return workers;
	}

	public static Worker getWorker() {

		synchronized (workers) {

			while (workers.size() == 0) {

				try {
					workers.wait();
				} catch (InterruptedException e) {
				}
			}

			return workers.remove(0);
		}
	}

	public static void freeWorker(Worker worker) {

		synchronized (workers) {

			workers.add(worker);
			workers.notify();
		}
	}
}
